﻿using SaaS.Model.Dto.Sites;
using StackExchange.Redis;
using XCore.Dependency;
using XCore.Redis;

namespace SaaS.Cache.Sites
{
    public class SiteCacheService : CacheServiceBase, ISingletonDependency
    {
        protected override int Db => 2;
        /// <summary>
        /// 站点信息
        /// </summary>
        private const string SITE_INFO = "SITE_INFO:";
        /// <summary>
        /// 保存前缀与站点ID的关系
        /// </summary>
        private const string SITE_DOMAIN = "SITE_DOMAIN";
        private const string TENANT_NAME = "TENANT_NAME";
        private const string TENANT_SECRETKEY = "TENANT_SECRETKEY";
        private const string TENANT_ID = "TENANT_ID";

        /// <summary>
        /// 根据域名前缀获取站点ID
        /// </summary>
        /// <param name="domain"></param>
        /// <returns></returns>
        public int GetSiteId(string domain)
        {
            return Redis.HashGet(SITE_DOMAIN, domain).GetRedisValue<int>();
        }
        /// <summary>
        /// 保存站点信息
        /// </summary>
        /// <param name="site"></param>
        public void SaveSiteInfo(SiteModel site)
        {
            string key = SITE_INFO + site.SiteId;
            IBatch batch = Redis.CreateBatch();
            batch.HashSetAsync(key, site);
            string domain = site.Domain ?? site.Domain.ToString();
            batch.HashSetAsync(SITE_DOMAIN, domain, site.SiteId);
            batch.Execute();
        }
        /// <summary>
        /// 获取站点信息
        /// </summary>
        /// <param name="siteId"></param>
        /// <returns></returns>
        public SiteModel GetSiteInfo(int siteId)
        {
            string key = SITE_INFO + siteId;
            return Redis.HashGetAll(key);
        }
        public string GetName(int id)
        {
            return this.GetHash<string>(TENANT_NAME, id.ToString());
        }

        public void SecretKey(int id, string secretKey)
        {
            IBatch batch = Redis.CreateBatch();
            batch.HashDeleteAsync(TENANT_SECRETKEY, id);
            batch.HashDeleteAsync(TENANT_ID, secretKey);
            batch.HashSetAsync(TENANT_SECRETKEY, id, secretKey);
            batch.HashSetAsync(TENANT_ID, secretKey, id);
            batch.Execute();
        }

        public string SecretKey(int id)
        {
            return this.GetHash<string>(TENANT_SECRETKEY, id.ToString());
        }

        /// <summary>
        /// 验证密钥是否有误
        /// </summary>
        /// <param name="secretKey"></param>
        /// <returns></returns>
        public bool IsSecretKey(string secretKey)
        {
            return Redis.HashExists(TENANT_ID, secretKey);
        }
    }
}
